const API_BASE_URL = '/api';

// 从localStorage获取token
function getToken() {
    return localStorage.getItem('token');
}

// 存储token
function setToken(token) {
    if (token) {
        localStorage.setItem('token', token);
    } else {
        localStorage.removeItem('token');
    }
}

/**
 * 增强的基础请求方法
 * @param {string} url - 请求地址
 * @param {string} method - 请求方法(GET/POST/PUT/DELETE)
 * @param {object} data - 请求数据
 * @param {object} headers - 自定义请求头
 * @returns {Promise} 返回Promise对象
 */
async function request(url, method = 'GET', data = null, headers = {}) {
    const token = getToken();
    if (token) {
        headers['Authorization'] = `Bearer ${token}`;
    }

    const options = {
        method,
        headers: {
            'Content-Type': 'application/json',
            ...headers
        },
        credentials: 'include'
    };

    if (data) {
        options.body = JSON.stringify(data);
    }

    try {
        const response = await fetch(`${API_BASE_URL}${url}`, options);

        // 处理无响应内容的情况
        if (response.status === 204) {
            return null;
        }

        const result = await response.json();

        if (!response.ok) {
            // 处理token过期情况
            if (response.status === 401) {
                setToken(null);
                UserManager.logout();
                window.location.href = '/login.html';
            }
            throw new Error(result.message || `请求失败: ${response.statusText}`);
        }

        // 登录成功时保存token
        if (url === '/users/login' && result.token) {
            setToken(result.token);
        }

        return result;
    } catch (error) {
        console.error('API请求错误:', error);
        throw error;
    }
}
/**
 * 用户认证模块
 */
const auth = {
    /**
     * 用户注册
     * @param {object} userData - 用户注册数据
     * @returns {Promise}
     */
    register: (userData) => request('/api/users/register', 'POST', userData),

    /**
     * 用户登录
     * @param {object} credentials - 登录凭证 {username, password}
     * @returns {Promise}
     */
    login: (credentials) => request('/api/users/login', 'POST', credentials),

    /**
     * 获取当前用户信息
     * @returns {Promise}
     */
    getCurrentUser: () => request('/api/users/current'),

    /**
     * 更新用户信息
     * @param {object} userData - 更新的用户数据
     * @returns {Promise}
     */
    updateUser: (userData) => request('/api/users', 'PUT', userData),

    /**
     * 删除用户
     * @param {number} userId - 用户ID
     * @returns {Promise}
     */
    deleteUser: (userId) => request(`/api/users/${userId}`, 'DELETE')
};

/**
 * 商品管理模块
 */
const products = {
    /**
     * 添加商品
     * @param {object} productData - 商品数据
     * @returns {Promise}
     */
    add: (productData) => request('/api/products', 'POST', productData),

    /**
     * 删除商品
     * @param {number} productId - 商品ID
     * @returns {Promise}
     */
    delete: (productId) => request(`/api/products/${productId}`, 'DELETE'),

    /**
     * 更新商品信息
     * @param {object} productData - 商品数据
     * @returns {Promise}
     */
    update: (productData) => request('/api/products', 'PUT', productData),

    /**
     * 获取单个商品详情
     * @param {number} productId - 商品ID
     * @returns {Promise}
     */
    get: (productId) => request(`/api/products/${productId}`),

    /**
     * 获取所有商品列表
     * @returns {Promise}
     */
    getAll: () => request('/api/products'),

    /**
     * 分页获取商品列表
     * @param {number} pageNum - 页码(从1开始)
     * @param {number} pageSize - 每页数量
     * @returns {Promise} 包含分页信息的响应数据
     */
    getByPage: (pageNum = 1, pageSize = 10, filters) =>
        request(`/api/products/page?pageNum=${pageNum}&pageSize=${pageSize}`),

    /**
     * 搜索商品
     * @param {string} keyword - 搜索关键词
     * @param {number} pageNum - 页码
     * @param {number} pageSize - 每页数量
     * @returns {Promise}
     */
    search: (keyword, pageNum = 1, pageSize = 10) =>
        request(`/api/products/search?keyword=${encodeURIComponent(keyword)}&pageNum=${pageNum}&pageSize=${pageSize}`),

    /**
     * 收藏商品
     * @param {string} productId - 商品ID
     * @returns {Promise}
     */
    favorite: (productId) => request(`/api/products/${productId}/favorite`, 'POST'),

    /**
     * 取消收藏商品
     * @param {number} productId - 商品ID
     * @returns {Promise}
     */
    unfavorite: (productId) => request(`/api/products/${productId}/favorite`, 'DELETE'),

    /**
     * 按分类分页获取商品列表
     * @param {number} categoryId - 分类ID
     * @param {number} pageNum - 页码(从1开始)
     * @param {number} pageSize - 每页数量
     * @returns {Promise} 包含分页信息的响应数据
     */
    getByCategory: (categoryId, pageNum = 1, pageSize = 10) =>
        request(`/api/products/category/${categoryId}?pageNum=${pageNum}&pageSize=${pageSize}`)
};

/**
 * 购物车模块
 */
const shoppingCart = {
    /**
     * 添加商品到购物车
     * @param {object} cartItem - 购物车项数据
     * @returns {Promise}
     */
    add: (cartItem) => request('/api/shopping-carts', 'POST', cartItem),

    /**
     * 从购物车移除商品
     * @param {number} cartItemId - 购物车项ID
     * @returns {Promise}
     */
    remove: (cartItemId) => request(`/api/shopping-carts/${cartItemId}`, 'DELETE'),

    /**
     * 更新购物车项
     * @param {object} cartItem - 购物车项数据
     * @returns {Promise}
     */
    update: (cartItem) => request('/api/shopping-carts', 'PUT', cartItem),

    /**
     * 获取单个购物车项
     * @param {number} cartItemId - 购物车项ID
     * @returns {Promise}
     */
    get: (cartItemId) => request(`/api/shopping-carts/${cartItemId}`),

    /**
     * 获取用户购物车所有商品
     * @param {number} userId - 用户ID
     * @param {number} pageNum - 页码
     * @param {number} pageSize - 每页数量
     * @returns {Promise}
     */
    getByUser: (userId, pageNum = 1, pageSize = 10) =>
        request(`/api/shopping-carts/user/${userId}?pageNum=${pageNum}&pageSize=${pageSize}`),

    /**
     * 获取所有购物车项
     * @returns {Promise}
     */
    getAll: () => request('/api/shopping-carts'),

    /**
     * 批量删除购物车项
     * @param {Array<number>} cartItemIds - 购物车项ID数组
     * @returns {Promise}
     */
    batchRemove: (cartItemIds) => request('/api/shopping-carts/batch', 'DELETE', { ids: cartItemIds })
};

/**
 * 订单模块
 */
const orders = {
    /**
     * 创建订单
     * @param {object} orderData - 订单数据
     * @returns {Promise}
     */
    create: (orderData) => request('/api/orders', 'POST', orderData),

    /**
     * 删除订单
     * @param {number} orderId - 订单ID
     * @returns {Promise}
     */
    delete: (orderId) => request(`/api/orders/${orderId}`, 'DELETE'),

    /**
     * 更新订单信息
     * @param {object} orderData - 订单数据
     * @returns {Promise}
     */
    update: (orderData) => request('/api/orders', 'PUT', orderData),

    /**
     * 获取单个订单详情
     * @param {number} orderId - 订单ID
     * @returns {Promise}
     */
    get: (orderId) => request(`/api/orders/${orderId}`),

    /**
     * 获取所有订单列表
     * @returns {Promise}
     */
    getAll: () => request('/api/orders'),

    /**
     * 分页获取订单列表
     * @param {number} pageNum - 页码
     * @param {number} pageSize - 每页数量
     * @returns {Promise}
     */
    getByPage: (pageNum = 1, pageSize = 10) =>
        request(`/api/orders?pageNum=${pageNum}&pageSize=${pageSize}`),

    /**
     * 获取用户订单
     * @param {number} userId - 用户ID
     * @param {number} pageNum - 页码
     * @param {number} pageSize - 每页数量
     * @returns {Promise}
     */
    getByUser: (userId, pageNum = 1, pageSize = 10) =>
        request(`/api/orders/user/${userId}?pageNum=${pageNum}&pageSize=${pageSize}`),

    /**
     * 取消订单
     * @param {number} orderId - 订单ID
     * @returns {Promise}
     */
    cancel: (orderId) => request(`/api/orders/${orderId}/cancel`, 'POST')
};

/**
 * 评价模块
 */
const ratings = {
    /**
     * 添加评价
     * @param {object} ratingData - 评价数据
     * @returns {Promise}
     */
    add: (ratingData) => request('/api/ratings', 'POST', ratingData),

    /**
     * 删除评价
     * @param {number} ratingId - 评价ID
     * @returns {Promise}
     */
    delete: (ratingId) => request(`/api/ratings/${ratingId}`, 'DELETE'),

    /**
     * 更新评价
     * @param {object} ratingData - 评价数据
     * @returns {Promise}
     */
    update: (ratingData) => request('/api/ratings', 'PUT', ratingData),

    /**
     * 获取单个评价详情
     * @param {number} ratingId - 评价ID
     * @returns {Promise}
     */
    get: (ratingId) => request(`/api/ratings/${ratingId}`),

    /**
     * 获取所有评价列表
     * @returns {Promise}
     */
    getAll: () => request('/api/ratings'),

    /**
     * 分页获取评价列表
     * @param {number} pageNum - 页码
     * @param {number} pageSize - 每页数量
     * @returns {Promise}
     */
    getByPage: (pageNum = 1, pageSize = 10) =>
        request(`/api/ratings?pageNum=${pageNum}&pageSize=${pageSize}`),

    /**
     * 获取商品评价
     * @param {number} productId - 商品ID
     * @param {number} pageNum - 页码
     * @param {number} pageSize - 每页数量
     * @returns {Promise}
     */
    getByProduct: (productId, pageNum = 1, pageSize = 10) =>
        request(`/api/ratings/product/${productId}?pageNum=${pageNum}&pageSize=${pageSize}`),

    /**
     * 获取用户评价
     * @param {number} userId - 用户ID
     * @param {number} pageNum - 页码
     * @param {number} pageSize - 每页数量
     * @returns {Promise}
     */
    getByUser: (userId, pageNum = 1, pageSize = 10) =>
        request(`/api/ratings/user/${userId}?pageNum=${pageNum}&pageSize=${pageSize}`)
};

/**
 * 商品分类模块
 */
const categories = {
    /**
     * 添加分类
     * @param {object} categoryData - 分类数据
     * @returns {Promise}
     */
    add: (categoryData) => request('/api/categories', 'POST', categoryData),

    /**
     * 删除分类
     * @param {number} categoryId - 分类ID
     * @returns {Promise}
     */
    delete: (categoryId) => request(`/api/categories/${categoryId}`, 'DELETE'),

    /**
     * 更新分类信息
     * @param {object} categoryData - 分类数据
     * @returns {Promise}
     */
    update: (categoryData) => request('/api/categories', 'PUT', categoryData),

    /**
     * 获取单个分类详情
     * @param {number} categoryId - 分类ID
     * @returns {Promise}
     */
    get: (categoryId) => request(`/api/categories/${categoryId}`),

    /**
     * 获取所有分类列表
     * @returns {Promise}
     */
    getAll: () => request('/api/categories'),

    /**
     * 分页获取分类列表
     * @param {number} pageNum - 页码
     * @param {number} pageSize - 每页数量
     * @returns {Promise}
     */
    getByPage: (pageNum = 1, pageSize = 10) =>
        request(`/api/categories?pageNum=${pageNum}&pageSize=${pageSize}`)
};

// 文件上传模块
const upload = {
    /**
     * 上传图片
     * @param {FormData} formData - 包含图片文件的FormData
     * @returns {Promise}
     */
    image: (formData) => {
        const options = {
            method: 'POST',
            body: formData
        };
        return request('/api/upload/image', options);
    }
};

export default {
    request,
    auth,
    products,
    shoppingCart,
    orders,
    ratings,
    categories,
    upload
};

document.addEventListener('DOMContentLoaded', function () {
    const userStr = localStorage.getItem('user');
    const authLink = document.getElementById('auth-link');
    const authText = document.getElementById('auth-text');
    const userAvatar = document.getElementById('user-avatar');

    if (userStr && authLink && authText && userAvatar) {
        const user = JSON.parse(userStr);
        authLink.href = 'user.html';
        authText.textContent = user.username || user.nickname || '个人中心';
        userAvatar.src = user.avatar || 'images/default-avatar.jpg';
        userAvatar.style.display = 'inline-block';
    } else if (authLink && authText && userAvatar) {
        authLink.href = 'login.html';
        authText.textContent = '登录/注册';
        userAvatar.src = '';
        userAvatar.style.display = 'none';
    }
});

document.addEventListener('DOMContentLoaded', function () {
    const userStr = localStorage.getItem('user');
    if (!userStr) {
        alert('请先登录');
        window.location.href = 'login.html';
        return;
    }
    const user = JSON.parse(userStr);
    document.getElementById('username-display').textContent = user.username || user.nickname;
    document.getElementById('user-avatar').src = user.avatar || 'images/default-avatar.jpg';
    // 其它信息同理
});